'use strict'

const router=require('koa-router')();
const fs=require('fs')

function getRouteFiles(filePath){
    let tmpPath=filePath || __dirname;

    let files=fs.readdirSync(tmpPath);

    let resFiles=files.filter(item=>{
        return item.endsWith('.js') && item !== 'index.js'
    })
    return resFiles;
}


function registerRoute(router,resFiles){
    resFiles.forEach(item=>{
        let tmpPath=__dirname+'/'+item;
        let obj=require(tmpPath)
        for(let key in obj){
            let tmpArr=key.split(' ')
            let routeUrl=tmpArr[1];
            let routeMethod=tmpArr[0];
            let routeFunction=obj[key]
            if(routeMethod==='get'){
                router.get(routeUrl,routeFunction)
            }else if(routeMethod==='post'){
                router.post(routeUrl,routeFunction)
            }else if(routeMethod==='put'){
                router.put(routeUrl,routeFunction)
            }else if(routeMethod==='delete'){
                router.delete(routeUrl,routeFunction)
            }
        }
    })
    return router.routes()
}

module.exports=function(){
    let resFiles=getRouteFiles();
    let fn=registerRoute(router,resFiles)
    return fn
}